/*
 * Copyright (c) 2018, apexes.net. All rights reserved.
 *
 *         http://www.apexes.net
 *
 */
package net.apexes.commons.ormlite;

import net.apexes.commons.ormlite.DatabaseHelper.ChangeSupportable;

import java.util.LinkedHashSet;
import java.util.Set;

/**
 * 
 * @author <a href="mailto:hedyn@foxmail.com">HeDYn</a>
 *
 */
public abstract class AbstractChangeSupport implements ChangeSupportable {
    
    private final ThreadLocal<Set<Table<?>>> mThreadLocal;
    
    protected AbstractChangeSupport() {
        mThreadLocal = new ThreadLocal<>();
    }

    @Override
    public final void addChange(Table<?> table) {
        Set<Table<?>> tables = mThreadLocal.get();
        if (tables == null) {
            tables = new LinkedHashSet<>();
            mThreadLocal.set(tables);
        }
        tables.add(table);
    }

    @Override
    public final boolean isChange() {
        Set<Table<?>> tables = mThreadLocal.get();
        if (tables == null) {
            return false;
        }
        return !tables.isEmpty();
    }

    @Override
    public final void clearChange() {
        Set<Table<?>> tables = mThreadLocal.get();
        if (tables == null) {
            return;
        }
        tables.clear();
    }

    @Override
    public final void notifyChange() {
        Set<Table<?>> tables = mThreadLocal.get();
        if (tables == null) {
            return;
        }
        mThreadLocal.set(null);
        notifyChange(tables.toArray(new Table<?>[0]));
    }
    
    protected abstract void notifyChange(Table<?>... tables);

}
